#!/bin/bash
# acetone, 2022

# Bypass addresses (home server, etc) splitting by whitespace
# Example: EXCLUDED=(8.8.8.8 1.1.1.1)
EXCLUDED=()

# Remove default gateway after 'disable' call
KILLSWITCH=true

###########

# funcs

isRoot() {
	if [ "$EUID" -ne 0 ]; then
		echo ""
		echo "Run as root"
		exit 1
	fi
}

initVars() {
	export GW_ADDRESS=$(cat /tmp/gw_address)
	export GW_DEV=$(cat /tmp/gw_dev)
	if [[ $GW_ADDRESS == "" ]] || [[ $GW_DEV == "" ]]; then
	        export GW_ADDRESS=$(ip route | grep default | awk '{print $3}')
        	export GW_DEV=$(ip route | grep default | awk '{print $5}')
		echo -e "$GW_ADDRESS" > /tmp/gw_address
		echo -e "$GW_DEV" > /tmp/gw_dev
	fi
}

varsInited() {
	if [[ $GW_ADDRESS == "" ]] || [[ $GW_DEV == "" ]]; then
		echo ""
		echo "Gateway values is undefined"
		exit 1
	fi
}

disable() {
	isRoot

	if [[ $KILLSWITCH == "true" ]]; then
		ip route del default
	fi

	for i in "${!EXCLUDED[@]}"
	do
		addr=${EXCLUDED[i]}
		ip route del $addr/32 via $GW_ADDRESS dev $GW_DEV
		echo -e "Custom route for $addr removed"
	done
}

enable() {
	isRoot

        for i in "${!EXCLUDED[@]}"
        do
                addr=${EXCLUDED[i]}
                ip route add $addr/32 via $GW_ADDRESS dev $GW_DEV
                echo -e "Custom route for $addr setted"
        done

        if [[ $KILLSWITCH == "true" ]] && [[ $(ip route | grep default) == "" ]]; then
                ip route add default via $GW_ADDRESS dev $GW_DEV
        fi
}

# init

initVars
varsInited

echo -e "Default gateway address: $GW_ADDRESS"
echo -e "Default gateway device: $GW_DEV"
echo    "Bypass list (always via native gateway):"

for i in "${!EXCLUDED[@]}"
do
        addr=${EXCLUDED[i]}
        echo -e "* $i\t $addr"
done

# args parsing

if [[ $1 == "disable" ]]; then
	disable
elif [[ $1 == "enable" ]]; then
	enable
else
	echo ""
	echo "Possible parameters: 'enable' and 'disable'"
fi